package com.aglhz.nature.view;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import com.aglhz.nature.R;
import com.aglhz.nature.events.AroundViewEvent;
import com.aglhz.nature.utils.AMapUtil;
import com.aglhz.nature.utils.ToastUtil;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnCameraChangeListener;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.AMap.OnMapTouchListener;
import com.amap.api.maps.AMapException;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.LocationSource.OnLocationChangedListener;
import com.amap.api.maps.SupportMapFragment;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.NaviPara;
import com.amap.api.maps.overlay.PoiOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;



import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class PoiKeywordSearchActivity extends FragmentActivity implements OnCheckedChangeListener,
OnMapTouchListener, OnMapClickListener, LocationSource, AMapLocationListener, OnMarkerClickListener, InfoWindowAdapter, OnPoiSearchListener ,OnClickListener,OnGeocodeSearchListener
{
	
	private String addressName;
	private GeocodeSearch geocoderSearch;
	private String keyWord = "";// 要输入的poi搜索关键字
	private PoiResult poiResult; // poi返回的结果
	private PoiSearch.Query query;// Poi查询条件类
	private PoiSearch poiSearch;// POI搜索
	private EditText poi_search;
	private Button searchButton;
	private Button sendButton;
	public AMapLocationClient mLocationClient = null;
	private AMap aMap;
	private MapView mapView;
	private OnLocationChangedListener mListener;
	private AMapLocationClient mlocationClient;
	private AMapLocationClientOption mLocationOption;
	private RadioGroup mGPSModeGroup;
	double lat;
	double lon;
	private TextView mLocationErrText;
	private Marker marker;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//requestWindowFeature(Window.FEATURE_NO_TITLE);// 不显示程序的标题栏
		setContentView(R.layout.locationmodesource_activity);
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		EventBus.getDefault().register(this);
		//先定位
//		lat=AroundActivity.lat;
//		lon=AroundActivity.lon;
		getLOcation();
//		init();
	}

	/**
	 * 初始化
	 */
	private void init() {
		if (aMap == null) {
			aMap = mapView.getMap();
			
			
			LatLng latLing= new LatLng(lat,lon);
			Log.e("经纬度",lat+"---"+lon);
			CameraUpdate cameraUpdate=CameraUpdateFactory.changeLatLng(latLing);
			aMap.moveCamera(cameraUpdate);
			
			marker = aMap.addMarker(new MarkerOptions().position(
					new LatLng(lat, lon)).icon(
					BitmapDescriptorFactory.fromResource(R.drawable.ditu)));
			
			setUpMap();
		}
		mGPSModeGroup = (RadioGroup) findViewById(R.id.gps_radio_group);
		mGPSModeGroup.setOnCheckedChangeListener(this);
		mLocationErrText = (TextView)findViewById(R.id.location_errInfo_text);
		mLocationErrText.setVisibility(View.GONE);
	}

	/**
	 * 设置一些amap的属性
	 */
	private void setUpMap() {
		aMap.moveCamera(CameraUpdateFactory.zoomTo(14));
		aMap.setOnMapTouchListener(this);
		aMap.setOnMapClickListener(this);// 对amap添加单击地图事件监听器
		aMap.getMaxZoomLevel();
		aMap.getMinZoomLevel();
		Log.e("aMap.getMaxZoomLevel()","---"+aMap.getMaxZoomLevel()+"--"+aMap.getMinZoomLevel());
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		// 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
		
		Button searButton = (Button) findViewById(R.id.searchButton);
		searButton.setOnClickListener(this);
		poi_search = (EditText)findViewById(R.id.poi_search);	
		sendButton=(Button) findViewById(R.id.sendButton);
		sendButton.setOnClickListener(this);		
		aMap.setOnMarkerClickListener(this);// 添加点击marker监听事件
		aMap.setInfoWindowAdapter(this);// 添加显示infowindow监听事件
		aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
	
		
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.gps_locate_button:
			// 设置定位的类型为定位模式
			aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
			break;
		case R.id.gps_follow_button:
			// 设置定位的类型为 跟随模式
			aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
			break;
		case R.id.gps_rotate_button:
			// 设置定位的类型为根据地图面向方向旋转
			aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);
			break;
		}

	}
	

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
		deactivate();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
		EventBus.getDefault().unregister(this);
		if(null != mlocationClient){
			mlocationClient.onDestroy();
		}
	}

	/**
	 * 定位成功后回调函数
	 */
	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		if (mListener != null && amapLocation != null) {
			if (amapLocation != null
					&& amapLocation.getErrorCode() == 0) {
				mLocationErrText.setVisibility(View.GONE);
//				mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
				
//				aMap.moveCamera(CameraUpdateFactory.zoomTo(14));
				
			} else {
				String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
				Log.e("AmapErr",errText);
				mLocationErrText.setVisibility(View.VISIBLE);
				mLocationErrText.setText(errText);
			}
		}
	}

	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mlocationClient == null) {
			mlocationClient = new AMapLocationClient(this);
			mLocationOption = new AMapLocationClientOption();
			//设置定位监听
			mlocationClient.setLocationListener(this);
			//设置为高精度定位模式
			mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
			//设置定位参数
			mlocationClient.setLocationOption(mLocationOption);
			// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
			// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
			// 在定位结束后，在合适的生命周期调用onDestroy()方法
			// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
			mlocationClient.startLocation();
		}
	}

	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		mListener = null;
		if (mlocationClient != null) {
			mlocationClient.stopLocation();
			mlocationClient.onDestroy();
		}
		mlocationClient = null;
	}




	
	
	/**
	 * 对触摸地图事件回调
	 */
	@Override
	public void onTouch(MotionEvent event) {

//		Log.e("触摸事件：屏幕位置", event.getX() + " ----" + event.getY());
	}
	
	
	/**
	 * 对单击地图事件回调
	 */
	@Override
	public void onMapClick(LatLng point) {
		Log.e("tapped, point=" , point.toString());
		aMap.clear(true);
		marker = aMap.addMarker(new MarkerOptions().position(
				new LatLng(point.latitude, point.longitude)).icon(
				BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
		lat=point.latitude;
		lon=point.longitude;
		Log.e("tapped, point=" , point.latitude+"---"+point.longitude);
	}


	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEventAroundThread(AroundViewEvent event) {

		String msg = event.getMessage();
		Log.i("定位", " AroundViewEvent:" + msg);
		// update UI By event
		if ( AroundViewEvent.EVENT_UPDATE_AROUND_LISTVIEW == msg) {
			// update grid view
			init();
		} 
		

	}
	

	public void getLOcation(){
		//初始化定位
			mLocationClient = new AMapLocationClient(getApplicationContext());
			//设置定位回调监听
			mLocationClient.setLocationListener(new AMapLocationListener(){

				@Override
				public void onLocationChanged(AMapLocation amapLocation) {
					if (amapLocation != null) {
				        if (amapLocation.getErrorCode() == 0) {
				        //定位成功回调信息，设置相关消息
				        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
				        amapLocation.getLatitude();//获取纬度
				        amapLocation.getLongitude();//获取经度
				        amapLocation.getAccuracy();//获取精度信息
				        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				        Date date = new Date(amapLocation.getTime());
				        df.format(date);//定位时间
				        amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
				        amapLocation.getCountry();//国家信息
				        amapLocation.getProvince();//省信息
				        amapLocation.getCity();//城市信息
				        amapLocation.getDistrict();//城区信息
				        amapLocation.getStreet();//街道信息
				        amapLocation.getStreetNum();//街道门牌号信息
				        amapLocation.getCityCode();//城市编码
				        amapLocation.getAdCode();//地区编码
				        amapLocation.getAoiName();//获取当前定位点的AOI信息	
				        lat= amapLocation.getLatitude();
				        lon= amapLocation.getLongitude();
				    	Log.e("经纬度qqq",lat+"---"+lon);
				    	
				    	 // send event
						 AroundViewEvent event = new   AroundViewEvent(
								 AroundViewEvent.EVENT_UPDATE_AROUND_LISTVIEW);
						 EventBus.getDefault().post(event);
						 
				        mLocationClient.stopLocation();//停止定位
				    
				    } else {
				    	 
				    	   mLocationClient.stopLocation();//停止定位
				              //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
				        Log.e("AmapError","location Error, ErrCode:"
				            + amapLocation.getErrorCode() + ", errInfo:"
				            + amapLocation.getErrorInfo());
				        }
				    }
					deactivate();
				  }
				
			});
			

			//初始化定位参数
			mLocationOption = new AMapLocationClientOption();
			//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
			mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
			//设置是否返回地址信息（默认返回地址信息）
			mLocationOption.setNeedAddress(true);
			//设置是否只定位一次,默认为false
			mLocationOption.setOnceLocation(false);
			//设置是否强制刷新WIFI，默认为强制刷新
			mLocationOption.setWifiActiveScan(true);
			//设置是否允许模拟位置,默认为false，不允许模拟位置
			mLocationOption.setMockEnable(false);
			//设置定位间隔,单位毫秒,默认为2000ms
			mLocationOption.setInterval(2000);
			//给定位客户端对象设置定位参数
			mLocationClient.setLocationOption(mLocationOption);
			//启动定位
			mLocationClient.startLocation();
	}
	
	
	
	
	
	
	

	/**
	 * 点击搜索按钮
	 */
	public void searchButton() {
		keyWord =poi_search.getText().toString().trim();
		if ("".equals(keyWord)) {
			ToastUtil.show(PoiKeywordSearchActivity.this, "请输入搜索关键字");
			return;
		} else {
			aMap.clear(true);
			getLatlon(keyWord);
//			doSearchQuery();
		}
	}
	
	
	/**
	 * 响应地理编码
	 */
	public void getLatlon(final String name) {
		geocoderSearch = new GeocodeSearch(this); 
		geocoderSearch.setOnGeocodeSearchListener(this);
		Log.e("响应地理编码","--------1------");
		GeocodeQuery query = new GeocodeQuery(name, "");// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
		Log.e("响应地理编码","---------2-----");
		
		geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
		Log.e("响应地理编码","----------3----");
	}
	
	/**
	 * 地理编码查询回调
	 */
	@Override
	public void onGeocodeSearched(GeocodeResult result, int rCode) {

		if (rCode == 1000) {
			if (result != null && result.getGeocodeAddressList() != null
					&& result.getGeocodeAddressList().size() > 0) {
				GeocodeAddress address = result.getGeocodeAddressList().get(0);
				aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
						AMapUtil.convertToLatLng(address.getLatLonPoint()), 15));
				marker.setPosition(AMapUtil.convertToLatLng(address
						.getLatLonPoint()));
//				addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:"
//						+ address.getFormatAddress();
				aMap.clear(true);
				marker = aMap.addMarker(new MarkerOptions().position(
						new LatLng(address.getLatLonPoint().getLatitude(), address.getLatLonPoint().getLongitude())).icon(
						BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
				lat=address.getLatLonPoint().getLatitude();
				lon=address.getLatLonPoint().getLongitude();
				
				Log.e("经纬度值",address.getLatLonPoint().toString());
			} else {
				ToastUtil.show(PoiKeywordSearchActivity.this, "没有搜索结果");
			}
		} else {
			ToastUtil.showerror(this, rCode);
		}
	}
	/**
	 * 开始进行poi搜索
	 */
	protected void doSearchQuery() {

		query = new PoiSearch.Query(keyWord, "", "");// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
		query.setPageSize(1);// 设置每页最多返回多少条poiitem
		poiSearch = new PoiSearch(this, query);
		poiSearch.setOnPoiSearchListener(this);
		poiSearch.searchPOIAsyn();
	}
	
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		/**
		 * 点击搜索按钮
		 */
		case R.id.searchButton:
			
			searchButton();
			break;
		case R.id.sendButton:
			Intent intent=new Intent(PoiKeywordSearchActivity.this,AroundActivity.class);
			intent.putExtra("lon", lon); 
			
			intent.putExtra("lat", lat);
			Log.e("intent",lon+"--"+lat);
			startActivity(intent);
			finish();
			break;
			
		default:
			break;
		}
	}


	@Override
	public View getInfoContents(Marker arg0) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public View getInfoWindow(final Marker marker) {
		View view = getLayoutInflater().inflate(R.layout.poikeywordsearch_uri,
				null);
		TextView title = (TextView) view.findViewById(R.id.title);
		title.setText(marker.getTitle());

		TextView snippet = (TextView) view.findViewById(R.id.snippet);
		snippet.setText(marker.getSnippet());
		ImageButton button = (ImageButton) view
				.findViewById(R.id.start_amap_app);
		// 调起高德地图app
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startAMapNavi(marker);
			}
		});
		return view;
	}
	/**
	 * 调起高德地图导航功能，如果没安装高德地图，会进入异常，可以在异常中处理，调起高德地图app的下载页面
	 */
	public void startAMapNavi(Marker marker) {
		// 构造导航参数
		NaviPara naviPara = new NaviPara();
		// 设置终点位置
		naviPara.setTargetPoint(marker.getPosition());
		// 设置导航策略，这里是避免拥堵
		naviPara.setNaviStyle(NaviPara.DRIVING_AVOID_CONGESTION);

		// 调起高德地图导航
		try {
			AMapUtils.openAMapNavi(naviPara, getApplicationContext());
		} catch (AMapException e) {

			// 如果没安装会进入异常，调起下载页面
			AMapUtils.getLatestAMapApp(getApplicationContext());

		}

	}
	/**
	 * 判断高德地图app是否已经安装
	 */
	public boolean getAppIn() {
		PackageInfo packageInfo = null;
		try {
			packageInfo = this.getPackageManager().getPackageInfo(
					"com.autonavi.minimap", 0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		// 本手机没有安装高德地图app
		if (packageInfo != null) {
			return true;
		}
		// 本手机成功安装有高德地图app
		else {
			return false;
		}
	}

	/**
	 * 获取当前app的应用名字
	 */
	public String getApplicationName() {
		PackageManager packageManager = null;
		ApplicationInfo applicationInfo = null;
		try {
			packageManager = getApplicationContext().getPackageManager();
			applicationInfo = packageManager.getApplicationInfo(
					getPackageName(), 0);
		} catch (PackageManager.NameNotFoundException e) {
			applicationInfo = null;
		}
		String applicationName = (String) packageManager
				.getApplicationLabel(applicationInfo);
		return applicationName;
	}



	@Override
	public boolean onMarkerClick(Marker marker) {
		marker.showInfoWindow();
		return false;
	}


	@Override
	public void onPoiItemSearched(PoiItem arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onPoiSearched(PoiResult result, int rCode) {
	
		if (rCode == 1000) {
			if (result != null && result.getQuery() != null) {// 搜索poi的结果
				if (result.getQuery().equals(query)) {// 是否是同一条
					poiResult = result;
					// 取得搜索到的poiitems有多少页
					List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
					List<SuggestionCity> suggestionCities = poiResult
							.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息

					if (poiItems != null && poiItems.size() > 0) {
						aMap.clear();// 清理之前的图标
						PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
						poiOverlay.removeFromMap();
						poiOverlay.addToMap();
						poiOverlay.zoomToSpan();
						for(PoiItem item : poiItems){
			                //获取经纬度对象
			                LatLonPoint llp = item.getLatLonPoint();
			                 lon = llp.getLongitude();
			                 lat = llp.getLatitude();
			                 Log.e("经纬度","--"+llp.getLatitude()+"--"+llp.getLongitude());
						}
					} else {
						ToastUtil.show(PoiKeywordSearchActivity.this,
								"对不起，没有搜索到相关数据！");
					}
				}
			} else {
				ToastUtil.show(PoiKeywordSearchActivity.this,
						"对不起，没有搜索到相关数据！");
			}
		} else {
			ToastUtil.showerror(this, rCode);
		}
		
	}


	
	
	/**
	 * 响应逆地理编码
	 */
	public void getAddress(final LatLonPoint latLonPoint) {
		
		RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,
				GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
		geocoderSearch.getFromLocationAsyn(query);// 设置同步逆地理编码请求
	}
	
	
	/**
	 * 逆地理编码回调
	 */
	@Override
	public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
	
		if (rCode == 1000) {
			if (result != null && result.getRegeocodeAddress() != null
					&& result.getRegeocodeAddress().getFormatAddress() != null) {
				addressName = result.getRegeocodeAddress().getFormatAddress()
						+ "附近";
				aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
						AMapUtil.convertToLatLng(new LatLonPoint(lat,lon)), 15));
				marker.setPosition(AMapUtil.convertToLatLng(new LatLonPoint(lat,lon)));
				ToastUtil.show(PoiKeywordSearchActivity.this, addressName);
			} else {
				ToastUtil.show(PoiKeywordSearchActivity.this, "对不起，没有搜索到相关数据！");
			}
		} else {
			ToastUtil.showerror(this, rCode);
		}
	}

}
